package org.example.login;

import org.junit.Before;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;

public class LoginTest {
    public static WebDriver webDriver;
    @BeforeAll
    public static void before() {
        webDriver = new ChromeDriver();
        webDriver.get("http://123.60.88.108:8080/login.html");
    }

    @ParameterizedTest
    @CsvFileSource(resources = "/login.csv", numLinesToSkip = 1)
    public void test(String username, String password) {

        WebElement element1 = webDriver.findElement(By.cssSelector("#username"));
        WebElement element2 = webDriver.findElement(By.cssSelector("#password"));
        //情况输入框
        element1.clear();
        element2.clear();

        //输入用户名
        element1.sendKeys(username);

        //输入密码
        element2.sendKeys(password);

        //点击登录
        WebElement element3 = webDriver.findElement(By.cssSelector("#submit"));
        element3.click();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        String currentUrl = webDriver.getCurrentUrl();
        String url = "http://123.60.88.108:8080/client.html";
        //检查是否登录成功
        if(url.equals(currentUrl)) {
                System.out.println("登录成功:{用户名：" + username + " 密码：" + password + "}");
        }else {
            //登录失败时获取弹窗内的信息
            Alert alert = webDriver.switchTo().alert();
            if(alert != null) {
                if(alert.getText().equals("登录失败！！！")) {
                    System.out.println("登录失败");
                }
                alert.accept();
            }
        }

    }
}
